﻿using DotnetSpider.Core.Pipeline;
using System;
using System.Collections.Generic;
using System.Text;
using DotnetSpider.Core;
using DotnetSpider.Core.Scheduler;

using System.Linq;
using SpiderPlatform.Entity;
using SpiderPlatform.Dao;
using SpiderPlatform.Processor;
using Yamibuy.Framework.Core.Tools;
namespace SpiderPlatform.Pipe
{
    public class KouhighPipe : BasePipeline
    {

        ItemDao dao = new ItemDao();
        List<ChannelItemEntity> itemlist = new List<ChannelItemEntity>();
        public KouhighPipe()
        {
          
        }

        public override void Process(IEnumerable<ResultItems> resultItems, ISpider spider)
        {
            List<ChannelItemHistoryEntity> hisList = new List<ChannelItemHistoryEntity>();
            foreach (var resultItem in resultItems)
            {
                var list = resultItem.Results["list"] as List<KouhighEntity>;
                foreach (var item in list)
                {
                    Logger.Info(item.name);

                    var temp = itemlist.FirstOrDefault(p => p.channel_sku == item.id);
                    hisList.Add(new ChannelItemHistoryEntity
                    {
                        channel_id = 5,
                        channel_sku = item.id,
                        score = 0,
                        is_instock = 1,
                        reviews = 0,
                        price = decimal.Parse(item.price.TrimStart('$')),
                        title = item.name,
                        link = item.link,
                        images = item.images,
                        sku = temp == null ? 0 : temp.sku
                    });
                }                
            }
            dao.CreateChannelItemHistory(hisList);
            var hisExists = dao.QueryChannelItemBySku(6, hisList.Select(p => p.channel_sku).ToList());
            //检查是否有新的商品出现
            var diffList = hisList.Except(hisExists, new ChannelItemHistoryComparer());
            //记录新的item
            var newItemList = diffList.ToList().ToTypeList<ChannelItemHistoryEntity, ChannelItemEntity>();
            if (newItemList.Count > 0)
            {
                dao.CreateChannelItem(newItemList);
                var realList = diffList.ToList();
                dao.CreateChannelItemRealTime(realList);
            }
            dao.UpdateChannelItemRealTime(hisList);
        }        
    }
}
